<template>
  <div class="form-designer">
    <div class="toolbar">
      <button @click="newForm" class="btn">新建表单</button>
      <button @click="saveForm" class="btn">保存表单</button>
      <button @click="deployForm" class="btn btn-primary">部署表单</button>
    </div>
    <div ref="formContainerRef" class="form-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { FormEditor } from '@bpmn-io/form-js-editor';
import { workflowService } from '../api/workflowService';

// 非常重要：确保正确导入所有必需的样式文件
import '@bpmn-io/form-js-editor/dist/assets/form-js-editor.css';
import '@bpmn-io/form-js/dist/assets/form-js.css';

let formEditor = null;
const formContainerRef = ref(null);

// 表单模板 - 根据截图创建Invoice表单模板
const getEmptyFormTemplate = () => {
  console.log('获取表单模板 - 尝试使用与截图一致的Invoice表单');
  
  // 这个模板使用与截图一致的Invoice表单结构
  return {
    type: 'default',
    id: 'Form_08nrbgf',
    components: [
      {
        type: 'text',
        key: 'header',
        label: 'File an Invoice',
        description: 'Add your invoice details below.',
        appearance: {
          level: 'h3'
        }
      },
      {
        type: 'textfield',
        key: 'creation',
        label: 'Creation*',
        validate: {
          required: true
        }
      },
      {
        type: 'textfield',
        key: 'invoiceNumber',
        label: 'Invoice Number',
        description: 'Invoice number in the form: C-123.'
      },
      {
        type: 'button',
        key: 'submit',
        label: 'Submit'
      }
    ]
  };
};

onMounted(() => {
  console.log('FormDesignerView mounted - 尝试初始化表单编辑器');
  initFormEditor();
});

onUnmounted(() => {
  if (formEditor) {
    formEditor.destroy();
    formEditor = null;
    console.log('FormEditor destroyed');
  }
});

// 为@bpmn-io/form-js-editor 1.17.0版本添加调色板和图标支持
const initFormEditor = () => {
  try {
    // 使用ref而不是getElementById，更符合Vue的最佳实践
    if (!formContainerRef.value) {
      console.error('表单容器未找到 (ref为空)');
      alert('错误：表单容器未找到');
      return;
    }

    // 确保容器有明确的尺寸
    const container = formContainerRef.value;
    container.style.width = '100%';
    container.style.height = '600px'; // 明确设置高度
    container.style.backgroundColor = '#ffffff';
    container.style.border = '1px solid #ddd';
    container.style.overflow = 'hidden';
    
    console.log('容器尺寸:', container.offsetWidth, 'x', container.offsetHeight);
    
    // 初始化表单编辑器，为1.17.0版本配置正确的参数
    formEditor = new FormEditor(container, {
      // @bpmn-io/form-js-editor 1.17.0版本使用这个配置启用属性面板
      propertiesPanel: {
        enabled: true
      },
      // 为了确保调色板正确显示，我们需要确保编辑器有完整的功能
      additionalModules: []
    });

    console.log('FormEditor实例创建成功 - 已配置调色板和属性面板');
    loadEmptyForm();
    
    // 延迟执行，确保编辑器完全初始化后再尝试显示调色板
    setTimeout(() => {
      ensurePaletteVisibility();
    }, 500);
  } catch (error) {
    console.error('初始化表单编辑器失败:', error);
    // 显示详细的错误信息
    alert(`初始化表单编辑器失败: ${error.name}: ${error.message}\n\n请查看控制台获取更多详细信息`);
  }
};

// 确保调色板可见的辅助函数
const ensurePaletteVisibility = () => {
  try {
    // 在DOM中查找调色板元素
    const paletteElement = document.querySelector('.fjs-palette');
    
    if (paletteElement) {
      console.log('调色板元素已找到，正在优化其显示');
      // 强制显示调色板
      paletteElement.style.display = 'block';
      paletteElement.style.visibility = 'visible';
      paletteElement.style.opacity = '1';
      paletteElement.style.minWidth = '200px';
      paletteElement.style.padding = '10px';
      paletteElement.style.backgroundColor = '#f8f9fa';
      paletteElement.style.borderRight = '1px solid #dee2e6';
      
      // 检查并确保调色板内容存在
      const paletteEntries = paletteElement.querySelectorAll('.fjs-palette__entry');
      if (paletteEntries.length === 0) {
        console.log('调色板内容为空，尝试手动添加基础组件');
        addBasicPaletteComponents(paletteElement);
      }
    } else {
      console.log('调色板元素未找到，尝试创建调色板容器');
      createCustomPalette();
    }
  } catch (error) {
    console.error('确保调色板可见时出错:', error);
  }
};

// 创建自定义调色板容器
const createCustomPalette = () => {
  try {
    // 找到编辑器容器
    const editorElement = document.querySelector('.fjs-editor');
    if (!editorElement) return;
    
    // 检查是否已有调色板容器
    let paletteContainer = editorElement.querySelector('.fjs-palette');
    
    if (!paletteContainer) {
      // 创建新的调色板容器
      paletteContainer = document.createElement('div');
      paletteContainer.className = 'fjs-palette';
      paletteContainer.style.display = 'flex';
      paletteContainer.style.flexDirection = 'column';
      paletteContainer.style.minWidth = '200px';
      paletteContainer.style.padding = '10px';
      paletteContainer.style.backgroundColor = '#f8f9fa';
      paletteContainer.style.borderRight = '1px solid #dee2e6';
      
      // 将调色板添加到编辑器容器的最前面
      editorElement.insertBefore(paletteContainer, editorElement.firstChild);
      
      // 调整编辑器内容区域的样式
      const contentElement = editorElement.querySelector('.fjs-editor__content');
      if (contentElement) {
        contentElement.style.marginLeft = '200px';
      }
      
      // 添加基础组件到调色板
      addBasicPaletteComponents(paletteContainer);
    }
  } catch (error) {
    console.error('创建自定义调色板时出错:', error);
  }
};

// 向调色板添加基础组件 - 与截图保持一致的组件分类
const addBasicPaletteComponents = (paletteContainer) => {
  try {
    // 定义基础组件组 - 按照截图中的分类
    const componentGroups = [
      {
        label: 'Input',
        components: [
          { type: 'textfield', label: 'Text field' },
          { type: 'textarea', label: 'Text area' },
          { type: 'number', label: 'Number' },
          { type: 'date', label: 'Date time' },
          { type: 'expression', label: 'Expression' },
          { type: 'file', label: 'File picker' }
        ]
      },
      {
        label: 'Selection',
        components: [
          { type: 'checkbox', label: 'Checkbox' },
          { type: 'checkbox', label: 'Checkbox group' },
          { type: 'radio', label: 'Radio group' },
          { type: 'select', label: 'Select' },
          { type: 'select', label: 'Tag list' }
        ]
      },
      {
        label: 'Presentation',
        components: [
          { type: 'text', label: 'Text view' },
          { type: 'image', label: 'Image view' },
          { type: 'table', label: 'Table' },
          { type: 'html', label: 'HTML view' },
          { type: 'document', label: 'Document preview' },
          { type: 'spacer', label: 'Spacer' }
        ]
      }
    ];
    
    // 清空调色板内容
    paletteContainer.innerHTML = '';
    
    // 添加组件组
    componentGroups.forEach(group => {
      // 创建组标签
      const groupLabel = document.createElement('div');
      groupLabel.className = 'fjs-palette__group-label';
      groupLabel.textContent = group.label;
      groupLabel.style.fontWeight = 'bold';
      groupLabel.style.color = '#495057';
      groupLabel.style.marginBottom = '8px';
      groupLabel.style.fontSize = '12px';
      groupLabel.style.textTransform = 'uppercase';
      paletteContainer.appendChild(groupLabel);
      
      // 创建组件条目容器
      const entriesContainer = document.createElement('div');
      entriesContainer.className = 'fjs-palette__entries';
      entriesContainer.style.display = 'grid';
      entriesContainer.style.gridTemplateColumns = '1fr 1fr';
      entriesContainer.style.gap = '8px';
      entriesContainer.style.marginBottom = '15px';
      paletteContainer.appendChild(entriesContainer);
      
      // 添加组件条目
      group.components.forEach(component => {
        const entry = document.createElement('div');
        entry.className = 'fjs-palette__entry';
        entry.dataset.type = component.type;
        entry.textContent = component.label;
        entry.style.padding = '8px';
        entry.style.border = '1px solid #dee2e6';
        entry.style.borderRadius = '4px';
        entry.style.backgroundColor = 'white';
        entry.style.cursor = 'pointer';
        entry.style.textAlign = 'center';
        entry.style.transition = 'all 0.2s ease';
        entry.style.fontSize = '12px';
        
        // 添加鼠标悬停效果
        entry.addEventListener('mouseenter', () => {
          entry.style.backgroundColor = '#e3f2fd';
          entry.style.borderColor = '#1976d2';
          entry.style.transform = 'translateY(-1px)';
        });
        
        entry.addEventListener('mouseleave', () => {
          entry.style.backgroundColor = 'white';
          entry.style.borderColor = '#dee2e6';
          entry.style.transform = 'translateY(0)';
        });
        
        // 添加点击事件，用于添加组件到表单
        entry.addEventListener('click', () => {
          addComponentToForm(component.type);
        });
        
        entriesContainer.appendChild(entry);
      });
    });
  } catch (error) {
    console.error('添加基础组件到调色板时出错:', error);
  }
};

// 向表单添加组件
const addComponentToForm = async (componentType) => {
  try {
    if (!formEditor) {
      console.error('FormEditor实例不存在');
      return;
    }
    
    // 获取当前表单schema
    const schema = await formEditor.getSchema();
    
    // 创建新组件
    const newComponent = {
      type: componentType,
      key: `${componentType}_${Date.now()}`,
      label: getDefaultLabelForComponent(componentType)
    };
    
    // 添加一些组件特定的默认属性
    if (componentType === 'select') {
      newComponent.values = [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' },
        { label: '选项3', value: 'option3' }
      ];
    } else if (['checkbox', 'radio'].includes(componentType)) {
      newComponent.values = [
        { label: '选项A', value: 'optionA' },
        { label: '选项B', value: 'optionB' },
        { label: '选项C', value: 'optionC' }
      ];
    }
    
    // 将新组件添加到schema
    if (!schema.components) {
      schema.components = [];
    }
    schema.components.push(newComponent);
    
    // 更新表单
    await formEditor.importSchema(schema);
    console.log(`已添加${componentType}组件到表单`);
  } catch (error) {
    console.error('添加组件到表单时出错:', error);
    alert(`添加组件失败: ${error.message || '未知错误'}`);
  }
};

// 获取组件的默认标签
const getDefaultLabelForComponent = (componentType) => {
  const labels = {
    text: '文本',
    textfield: '单行输入框',
    number: '数字输入',
    select: '下拉选择',
    checkbox: '复选框组',
    radio: '单选框组',
    group: '分组容器',
    grid: '网格布局',
    date: '日期选择',
    datetime: '日期时间选择',
    file: '文件上传',
    password: '密码输入'
  };
  
  return labels[componentType] || componentType;
};

const loadEmptyForm = () => {
  if (!formEditor) {
    console.error('FormEditor实例不存在');
    return;
  }

  try {
    const schema = getEmptyFormTemplate();
    console.log('准备加载表单模板:', schema);
    
    formEditor.importSchema(schema)
      .then(() => {
        console.log('表单模板加载成功!');
        // 验证编辑器是否正确渲染
        setTimeout(() => {
          console.log('验证表单编辑器渲染状态');
          // 强制重绘
          if (formContainerRef.value) {
            formContainerRef.value.style.display = 'none';
            requestAnimationFrame(() => {
              formContainerRef.value.style.display = 'block';
            });
          }
        }, 100);
      })
      .catch(err => {
        console.error('表单模板加载失败:', err);
        alert(`表单模板加载失败: ${err.name}: ${err.message}`);
      });
  } catch (error) {
    console.error('加载表单模板过程中发生错误:', error);
    alert(`加载表单模板时出错: ${error.name}: ${error.message}`);
  }
};

const newForm = () => {
  if (confirm('确定要创建新表单吗？未保存的内容将会丢失。')) {
    loadEmptyForm();
  }
};

const saveForm = async () => {
  if (!formEditor) return;

  try {
    const schema = await formEditor.getSchema();
    localStorage.setItem('lastForm', JSON.stringify(schema));
    alert('表单保存成功！');
  } catch (err) {
    console.error('保存表单失败:', err);
    alert(`保存表单失败: ${err.message || '未知错误'}`);
  }
};

const deployForm = async () => {
  if (!formEditor) return;

  try {
    const schema = await formEditor.getSchema();
    const result = await workflowService.deployForm({ formKey: `form_${Date.now()}`, schema: JSON.stringify(schema) });
    alert('表单部署成功！');
  } catch (err) {
    console.error('部署表单失败:', err);
    alert(`部署表单失败: ${err.message || '未知错误'}`);
  }
};
</script>

<style scoped>
/* 基础重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 简化的表单设计器容器样式 */
.form-designer {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  z-index: 1;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  z-index: 10;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.btn:hover {
  background-color: #f0f0f0;
}

.btn-primary {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

.btn-primary:hover {
  background-color: #35495e;
  border-color: #35495e;
}

/* 核心：表单容器样式 */
.form-container {
  flex: 1;
  width: 100%;
  min-height: 0; /* 重要：允许flex子元素正确收缩 */
  display: block; /* 使用block而不是flex，避免可能的样式冲突 */
  background-color: white;
  /* 确保内容可见的关键样式 */
  opacity: 1;
  visibility: visible;
  z-index: 1;
  position: relative;
}

/* 确保编辑器能正确显示的全局样式重置 */
:deep(.fjs-editor) {
  height: 100% !important;
  min-height: 100% !important;
  width: 100% !important;
  display: flex !important;
  flex-direction: column !important;
}

:deep(.fjs-editor__content) {
  flex: 1 !important;
  min-height: 0 !important;
}

/* 增强调色板样式 - 与截图保持一致 */
:deep(.fjs-palette) {
  background-color: #f8f9fa !important;
  border-right: 1px solid #dee2e6 !important;
  padding: 10px !important;
  min-width: 180px !important;
  overflow-y: auto;
}

:deep(.fjs-palette__group) {
  margin-bottom: 15px !important;
}

:deep(.fjs-palette__group-label) {
  font-weight: bold !important;
  color: #495057 !important;
  margin-bottom: 8px !important;
  font-size: 11px !important;
  text-transform: uppercase !important;
  letter-spacing: 0.5px;
}

:deep(.fjs-palette__entries) {
  display: flex !important;
  flex-direction: column !important;
  gap: 4px !important;
}

:deep(.fjs-palette__entry) {
  padding: 6px !important;
  border: 1px solid #dee2e6 !important;
  border-radius: 3px !important;
  background-color: white !important;
  cursor: pointer !important;
  text-align: left !important;
  transition: all 0.2s ease !important;
  font-size: 11px !important;
  display: flex !important;
  align-items: center !important;
  gap: 8px !important;
  height: 32px !important;
}

:deep(.fjs-palette__entry:hover) {
  background-color: #e3f2fd !important;
  border-color: #1976d2 !important;
  transform: none !important;
}

/* 添加组件图标支持 - 模拟Font Awesome图标 */
:deep(.fjs-palette__entry::before) {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

/* 为不同组件类型添加不同图标标识 */
:deep([data-type="textfield"])::before {
  content: "□";
  font-size: 14px;
}

:deep([data-type="textarea"])::before {
  content: "▭";
  font-size: 14px;
}

:deep([data-type="number"])::before {
  content: "#";
  font-size: 14px;
}

:deep([data-type="date"])::before {
  content: "📅";
  font-size: 14px;
}

:deep([data-type="expression"])::before {
  content: "{}";
  font-size: 14px;
}

:deep([data-type="file"])::before {
  content: "📎";
  font-size: 14px;
}

:deep([data-type="checkbox"])::before {
  content: "☑";
  font-size: 14px;
}

:deep([data-type="radio"])::before {
  content: "○";
  font-size: 14px;
}

:deep([data-type="select"])::before {
  content: "▼";
  font-size: 14px;
}

:deep([data-type="text"])::before {
  content: "ABC";
  font-size: 10px;
}

:deep([data-type="image"])::before {
  content: "🖼";
  font-size: 14px;
}

:deep([data-type="table"])::before {
  content: "📊";
  font-size: 14px;
}

:deep([data-type="html"])::before {
  content: "<>";
  font-size: 14px;
}

:deep([data-type="document"])::before {
  content: "📄";
  font-size: 14px;
}

:deep([data-type="spacer"])::before {
  content: "▬";
  font-size: 14px;
}

/* 增强表单编辑器布局 */
:deep(.fjs-editor) {
  display: flex !important;
  flex-direction: row !important;
  height: 100% !important;
}

:deep(.fjs-editor__content) {
  flex: 1 !important;
  display: flex !important;
  flex-direction: column !important;
  overflow: hidden !important;
}

:deep(.fjs-form) {
  flex: 1 !important;
  padding: 20px !important;
  overflow-y: auto !important;
  max-width: 800px !important;
  margin: 0 auto !important;
}

/* 增强属性面板样式 */
:deep(.fjs-properties-panel) {
  width: 280px !important;
  border-left: 1px solid #dee2e6 !important;
  background-color: #f8f9fa !important;
}

:deep(.fjs-properties-panel-header) {
  background-color: #343a40 !important;
  color: white !important;
  padding: 10px !important;
  font-size: 14px !important;
  font-weight: bold !important;
}

:deep(.fjs-palette__entry:hover) {
  background-color: #e3f2fd !important;
  border-color: #1976d2 !important;
  transform: translateY(-1px) !important;
}

/* 为表单元素添加图标支持 */
:deep(.fjs-component) {
  position: relative !important;
  margin-bottom: 16px !important;
}

:deep(.fjs-component__label) {
  display: block !important;
  font-weight: 500 !important;
  margin-bottom: 4px !important;
  color: #212529 !important;
}

:deep(.fjs-component__description) {
  font-size: 12px !important;
  color: #6c757d !important;
  margin-bottom: 8px !important;
}

:deep(.fjs-component__widget) {
  width: 100% !important;
  padding: 8px !important;
  border: 1px solid #ced4da !important;
  border-radius: 4px !important;
  font-size: 14px !important;
}

:deep(.fjs-button) {
  background-color: #6c757d !important;
  color: white !important;
  border: none !important;
  padding: 10px 20px !important;
  border-radius: 4px !important;
  cursor: pointer !important;
  font-size: 14px !important;
  margin-top: 8px !important;
}
</style>